package nio.bytebuffer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;

public class AllocateDirect_Cleaner {

    public static void main(String[] args) throws InterruptedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        System.out.println("A");
        ByteBuffer buffer = ByteBuffer.allocateDirect(Integer.MAX_VALUE);

        System.out.println("B");
        byte[] byteArray = new byte[] {1};
        System.out.println(Integer.MAX_VALUE);
        for (int i = 0; i < Integer. MAX_VALUE; i++) {
            buffer.put(byteArray);
        }
        System.out.println("put end!");

        Thread.sleep( 1000);

        /**
         * 占有非堆资源的对象实例，类应该提供一个方法以明确释放这些资源，
         * 如果合适的话他们也应该实现 AutoCloseable 接口；
         */
        Method cleanerMethod = buffer.getClass().getMethod("cleaner");
        cleanerMethod.setAccessible(true);
        Object returnValue = cleanerMethod.invoke(buffer);

        Method cleanMethod = returnValue.getClass().getMethod("clean");
        cleanMethod.setAccessible(true);
        cleanMethod.invoke(returnValue);
        // 此程序运行的效果就是 1 秒钟之后立即回收内存
        // 也就是回收“直接缓冲区”所占用的内存

    }

}
